package cn.tedu.ivos.base.security;

import cn.tedu.ivos.base.response.JsonResult;
import cn.tedu.ivos.base.response.StatusCode;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Service;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录情况下，权限不足的响应
 */
@Service
@Slf4j
public class CustomAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request,
                       HttpServletResponse response,
                       AccessDeniedException accessDeniedException)
            throws IOException, ServletException {

        //响应一个JsonResult
        log.debug("权限不足，响应JsonResult");
        //权限不足，禁止访问，HTTP响应状态是403 ---》官方默认的
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        response.setContentType("application/json;charset=UTF-8");

        response.getWriter().write(
                JSON.toJSONString(new JsonResult(StatusCode.OPERATION_FAILED)));
//        //获取响应的打印写手，用于写入响应内容
//        PrintWriter writer = response.getWriter();
//        //构建一个表示未登录的JSON结果对象
//        JsonResult result = new JsonResult(StatusCode.NOT_LOGIN);
//        //将JSON结果对象转换为JSON字符串并写入响应
//        writer.write(JSON.toJSONString(result));
//        //刷新写手并关闭它
//        writer.flush();
//        writer.close();

    }
}
